package arithmetic

import (
	"gitee.com/huanminabc/go-StrMathCalculate/register"
	"gitee.com/huanminabc/go-StrMathCalculate/structure"
	"gitee.com/huanminabc/go-utils/common"
	"reflect"
	"strconv"
	"strings"
)

type AddArithmeticCalculate struct {
	name          string                  //计算器名称
	priority      int                     //优先级
	calculateData structure.CalculateData //计算器数据
	result        string                  //计算结果

}

func init() {
	//注册计算器
	register.RegisterCalculate(&AddArithmeticCalculate{
		name:     "+",
		priority: 2,
	})
}

func (a *AddArithmeticCalculate) GetName() string {
	return a.name
}

func (a *AddArithmeticCalculate) IsBool(symbol string) bool {
	return symbol == a.name
}

func (a *AddArithmeticCalculate) AddExpression(a1, symbol, b1 string) {
	a.calculateData = structure.CalculateData{
		A:      a1,
		Symbol: symbol,
		B:      b1,
	}
}

func (a *AddArithmeticCalculate) Calculate() {

	b1 := common.IsNumber(a.calculateData.A)
	b2 := common.IsNumber(a.calculateData.B)
	if b1 && b2 {
		//判断是否是小数
		b3 := common.IsFloat(a.calculateData.A)
		b4 := common.IsFloat(a.calculateData.B)
		if b3 || b4 {
			//判断是数字
			A1, _ := strconv.ParseFloat(a.calculateData.A, 64)
			B1, _ := strconv.ParseFloat(a.calculateData.B, 64)
			a.result = strconv.FormatFloat(A1+B1, 'f', -1, 64)
		} else {
			//整数相加
			A1, _ := strconv.Atoi(a.calculateData.A)
			B1, _ := strconv.Atoi(a.calculateData.B)
			a.result = strconv.Itoa(A1 + B1)
			return
		}
	} else { //如果不是数字,那么就字符串相加
		var one = false
		//去掉双引号
		if strings.HasPrefix(a.calculateData.A, "\"") && strings.HasSuffix(a.calculateData.A, "\"") {
			a.calculateData.A = a.calculateData.A[1 : len(a.calculateData.A)-1]
		}
		if strings.HasPrefix(a.calculateData.B, "\"") && strings.HasSuffix(a.calculateData.B, "\"") {
			a.calculateData.B = a.calculateData.B[1 : len(a.calculateData.B)-1]
		}
		//去掉单引号
		if strings.HasPrefix(a.calculateData.A, "'") && strings.HasSuffix(a.calculateData.A, "'") {
			one = true
			a.calculateData.A = a.calculateData.A[1 : len(a.calculateData.A)-1]
		}
		if strings.HasPrefix(a.calculateData.B, "'") && strings.HasSuffix(a.calculateData.B, "'") {
			one = true
			a.calculateData.B = a.calculateData.B[1 : len(a.calculateData.B)-1]
		}
		//判断是否是字符串
		if reflect.TypeOf(a.calculateData.A).Kind() == reflect.String || reflect.TypeOf(a.calculateData.B).Kind() == reflect.String {
			//如果是单引号
			if one {
				a.result = "'" + a.calculateData.A + a.calculateData.B + "'"
				return
			} else {
				//字符串相加
				a.result = "\"" + a.calculateData.A + a.calculateData.B + "\""
				return
			}
		}
	}

}

func (a *AddArithmeticCalculate) GetResult() string {
	return a.result
}

func (a *AddArithmeticCalculate) GetPriority() int {
	return a.priority
}
